package controllers;

import play.*;
import play.cache.Cache;
import play.data.validation.Valid;
import play.db.jpa.Blob;
import play.i18n.Lang;
import play.libs.Crypto;
import play.libs.Images;
import play.libs.Mail;
import play.libs.OAuth2;
import play.mvc.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import models.*;
public class Speakrs extends Application {
	
		@Before
		static void checkUser() {
			
			if (connected() == null) {
				flash.error("Please log in first");
				Application.logar();
			}
		}
	
		public static void cadastrar(Speakr speakr) {
	    	
		   	 List<Experiencia> experiencias = Cache.get("experiencias", List.class);
		   	 
				  experiencias = Experiencia.all().fetch();
		        Cache.set("experiencias", experiencias, "30mn");
		        
		        List<Email> emails = Email.all().fetch();
		   	 
		        List<Speakr> speakrs = Speakr.all().fetch();
		        
		   	 render(experiencias,emails,speakr,speakrs);
		   }
   
    public static void cadastrarSpeakr(Speakr speakr) {
    	File outputFile = null;
    	    Blob usu_ima = speakr.spe_ima ;
    	    speakr.save();
            if (usu_ima != null){ 
            	
             outputFile = Play.getFile("/public/images/avatar/" + speakr.spe_nome+speakr.spe_codigo + ".jpg");
            Images.resize(usu_ima.getFile(), outputFile, 100, -1);
            speakr.spe_caminho_ima = "http://speakrs.me/public/images/avatar/" + speakr.spe_nome+speakr.spe_codigo + ".jpg";
            
        
           
   	    
            }
            
         
          
            speakr.save();
    	
            speakr = new Speakr();
    	cadastrar(speakr);
   }
    
 
    public static void alterSpeakr(@Valid Speakr user) {
		Blob spe_ima = user.spe_ima;
		user.save();

		FileInputStream iStream;
		if (spe_ima != null) {
			try {
				iStream = new FileInputStream(spe_ima.getFile());

				File outputFile = Play.getFile("/public/images/avatar/"
						+ user.spe_nome + user.spe_codigo + ".jpg");
				Images.resize(user.spe_ima.getFile(), outputFile, 100, -1);
				user.spe_caminho_ima = "http://speakrs.me/public/images/avatar/"
						+ user.spe_nome + user.spe_codigo + ".jpg";
				user.save();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		session.put("user", user.spe_nome);
		// Timeline.teste();
	}
    
    public static void perfil(Speakr ususario) {
    	List<Experiencia> experiencias = Experiencia.find("bySpe_codigo", ususario.spe_codigo).fetch();
    	
    	render(experiencias,ususario);
    }
    
}